{% extends "admin/base.html" %}

{% block stylesheets %}
{% endblock %}

{% block content %}
<div class="jumbotron">
	<div class="container">
		<h1>Teams
			<span class="create-team" role="button" data-toggle="tooltip" title="Create Team">
				<i class="btn-fa fas fa-plus-circle"></i>
			</span>
		</h1>
	</div>
</div>

<div id="email-user" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h2>Email Team</h2>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<form method="POST">
					<input type="hidden" name="id">
					<input type="hidden" name="nonce" value="{{ nonce }}">
					<textarea class="form-control" name="msg" placeholder="Enter your message here"
							  rows="15"></textarea>
					<br>
					<div id="email-user-errors"></div>
					<button type="button" id="send-user-email" class="btn btn-primary float-right">
						Send Message
					</button>
				</form>
			</div>
		</div>
	</div>
</div>

<div id="update-user-modal" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h2 class="modal-action">Edit Team</h2>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body clearfix">
				<form method="POST" action="{{ request.script_root }}/admin/teams/">
					<input type="hidden" name="nonce" value="{{ nonce }}">
					<input type="hidden" name="id">
					<div class="form-group">
						<label for="name">Team Name</label>
						<input type="text" class="form-control" name="name" id="name"
							   placeholder="Enter new team name" required>
					</div>
					<div class="form-group">
						<label for="email">Email</label>
						<input type="email" class="form-control" name="email" id="email"
							   placeholder="Enter new email" required>
					</div>
					<div class="form-group">
						<label for="password">Password</label>
						<input type="password" class="form-control" name="password" id="password"/>
					</div>
					<div class="form-group">
						<label for="website">Website</label>
						<input type="text" class="form-control" name="website" id="website"
							   placeholder="Enter website">
					</div>
					<div class="form-group">
						<label for="affiliation">Affiliation</label>
						<input type="text" class="form-control" name="affiliation" id="affiliation"
							   placeholder="Enter affiliation">
					</div>
					<div class="form-group">
						<label for="affiliation">Country</label>
						<input type="text" class="form-control" name="country" id="country"
							   placeholder="Enter country">
					</div>
					<div class="form-group">
						<div class="form-check form-check-inline">
							<input class="form-check-input" type="checkbox" name="admin" id="admin-checkbox">
							<label class="form-check-label" for="admin-checkbox">Admin</label>
						</div>
						<div class="form-check form-check-inline">
							<input class="form-check-input" type="checkbox" name="verified" id="verified-checkbox">
							<label class="form-check-label" for="verified-checkbox">Verified</label>
						</div>
						<div class="form-check form-check-inline">
							<input class="form-check-input" type="checkbox" name="hidden" id="hidden-checkbox">
							<label class="form-check-label" for="hidden-checkbox">Hidden</label>
						</div>
					</div>
					<div id="results">

					</div>
					<button id="update-user" type="submit"
							class="btn btn-primary btn-outlined float-right modal-action">Update
					</button>
				</form>
			</div>
		</div>
	</div>
</div>

<div class="container">
	<div class="row">
		<div class="col-md-12">
			{% if q and field%}
			<h4 class="text-center">Searching for teams with {{field}} matching {{q}}</h4>
			{% endif %}

			<form method="GET" class="form-inline">
					<div class="form-group col-md-2">
						<label for="sel1" class="sr-only" >Search Field</label>
						<select name="field" class="form-control w-100" id="sel1">
							<option value="name" {% if field == 'name' %}selected{% endif %}>Name</option>
							<option value="id" {% if field == 'id' %}selected{% endif %}>ID</option>
							<option value="email" {% if field == 'email' %}selected{% endif %}>Email</option>
							<option value="affiliation" {% if field == 'affiliation' %}selected{% endif %}>Affiliation</option>
							<option value="country" {% if field == 'country' %}selected{% endif %}>Country</option>
					  </select>
					</div>
					<div class="form-group col-md-8">
						<label for="team-name-search" class="sr-only">Parameter</label>
						<input type="text" class="form-control w-100" id="team-name-search" name="q" placeholder="Search for matching team names" {% if q %}value="{{q}}"{% endif %}>
					</div>
					<div class="form-group col-md-2">
						<label for="team-name-search" class="sr-only">Search</label>
						<button type="submit" class="btn btn-primary w-100"><i class="fas fa-search" aria-hidden="true"></i></button>
					</div>
			</form>

			<br>

			<table id="teamsboard" class="table table-striped">
				<thead>
					<tr>
						<td width="10px" class="text-center"><b>ID</b>
						</td>
						<td class="text-center"><b>Team</b>
						</td>
						<td class="d-none d-md-table-cell d-lg-table-cell text-center"><b>Email</b>
						</td>
						<td class="d-none"><b>Website</b>
						</td>
						<td class="d-none"><b>Affiliation</b>
						</td>
						<td class="d-none"><b>Country</b>
						</td>
						<td class="text-center"><b>Admin</b>
						</td>
						<td class="text-center"><b>Verified</b>
						</td>
						<td class="text-center"><b>Hidden</b>
						</td>
						<td class="text-center"><b>Settings</b>
						</td>
					</tr>
				</thead>
				<tbody>
					{% for team in teams %}
					<tr name="{{ team.id }}">
						<td class="team-id" value="{{ team.id }}">{{ team.id }}</td>
						<td class="team-name" value="{{ team.name }}"><a href="{{ request.script_root }}/admin/team/{{ team.id }}">{{ team.name | truncate(32) }}</a>
						</td>
						<td class="team-email d-none d-md-table-cell d-lg-table-cell" value="{{ team.email }}">{{ team.email | truncate(32) }}</td>
						<td class="team-website d-none text-center">
							{% if team.website %}
								<a href="{{ team.website }}" target="_blank">
									<i class="btn-fa fas fa-external-link-alt" data-toggle="tooltip" data-placement="top"
									   title="{{ team.website }}" aria-hidden="true"></i>
								</a>
							{% endif %}
						</td>
						<td class="team-affiliation d-none" value="{{ team.affiliation if team.affiliation is not none }}">
							<span>{% if team.affiliation %}{{ team.affiliation | truncate(20) }}{% endif %}</span>
						</td>
						<td class="team-country d-none" value="{{ team.country if team.country is not none }}">
							<span>{% if team.country %}{{ team.country }}{% endif %}</span>
						</td>
						<td class="team-admin d-none d-md-table-cell d-lg-table-cell text-center" value="{{ team.admin }}">
							{% if team.admin %}
								<span class="badge badge-primary">admin</span>
							{% endif %}
						</td>
						<td class="team-verified d-none d-md-table-cell d-lg-table-cell text-center" value="{{ team.verified }}">
							{% if team.verified %}
								<span class="badge badge-success">verified</span>
							{% endif %}
						</td>
						<td class="team-hidden d-none d-md-table-cell d-lg-table-cell text-center" value="{{ team.banned }}">
							{% if team.banned %}
								<span class="badge badge-danger">hidden</span>
							{% endif %}
						</td>
						<td class="text-center"><span>
							<span class="edit-team" data-toggle="tooltip" data-placement="top"
								  title="Modify {{ team.name }}">
								<i class="btn-fa fas fa-edit"></i>
							</span>
							{% if can_send_mail() %}
							<span class="email-team" data-toggle="tooltip" data-placement="top"
								  title="Email {{ team.name }}">
								<i class="btn-fa fas fa-envelope"></i>
							</span>
							{% endif %}
							<span class="delete-team" data-toggle="tooltip" data-placement="top"
								  title="Delete {{ team.name }}">
								<i class="btn-fa fas fa-times"></i>
							</span>
						</span>
						</td>
					</tr>
					{% endfor %}
				</tbody>
			</table>
			{% if pages > 1 %}
			<div class="text-center">Page
				<br>
				{% if curr_page != 1 %}<a href="{{ request.script_root }}/admin/teams/{{ curr_page-1 }}">&lt;&lt;&lt;</a>{% endif %}
				{% for page in range(1, pages + 1) %}
					{% if curr_page != page %}
						<a href="{{ request.script_root }}/admin/teams/{{ page }}">{{ page }}</a>
					{% else %}
						<b>{{ page }}</b>
					{% endif %}
				{% endfor %}
				{% if curr_page != pages %}<a href="{{ request.script_root }}/admin/teams/{{ curr_page + 1 }}">&gt;&gt;&gt;</a>{% endif %}
			</div>
			{% endif %}
		</div>
	</div>
</div>
{% endblock %}

{% block scripts %}
<script>
var nonce = "{{ nonce }}";

function load_update_modal(id, name, email, website, affiliation, country, admin, verified, hidden){
	var modal_form = $('#update-user-modal form');

	modal_form.find('input[name=name]').val(name);
	modal_form.find('input[name=id]').val(id);
	modal_form.find('input[name=email]').val(email);
	modal_form.find('input[name=website]').val(website);
	modal_form.find('input[name=affiliation]').val(affiliation);
	modal_form.find('input[name=country]').val(country);
	modal_form.find('input[name=password]').val('');

    modal_form.find('input[name=admin]').prop('checked', admin);
    modal_form.find('input[name=verified]').prop('checked', verified);
    modal_form.find('input[name=hidden]').prop('checked', hidden);

	if (id == 'new'){
		$('#update-user-modal .modal-action').text('Create Team');
	} else {
		$('#update-user-modal .modal-action').text('Edit Team');
	}

	$('#results').empty();
	$('#update-user-modal form').attr('action', '{{ request.script_root }}/admin/team/'+id);
	$('#update-user-modal').modal("show");
}


function load_email_modal(id){
	var modal = $('#email-user');
	modal.find('textarea').val("");
	modal.find('input[name=id]').val(id);
	$('#email-user-errors').empty();
	$('#email-user form').attr('action', '{{ request.script_root }}/admin/team/'+id+'/mail');
	$('#email-user').modal();
}


$(document).ready(function () {
    $('#update-user').click(function (e) {
        e.preventDefault();
        var id = $('#update-user-modal input[name="id"]').val()
        var user_data = $('#update-user-modal form').serializeArray()
        $('#results').empty();
        $.post($('#update-user-modal form').attr('action'), $('#update-user-modal form').serialize(), function (data) {
            var data = $.parseJSON(JSON.stringify(data))
            for (var i = 0; i < data['data'].length; i++) {
                if (data['data'][i] == 'success') {
                    $('#update-user-modal').modal('hide');
                    location.reload();
                }
                else {
                    var error = $('<div class="alert alert-danger alert-dismissable">\n' +
                        '  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>\n' +
                        '  {0}\n'.format(data['data'][i]) +
                        '</div>');
                    $('#results').append(error);
                }
            }
            ;
        })
    });

    $('#send-user-email').click(function (e) {
        e.preventDefault();
        var id = $('#email-user input[name="id"]').val();
        var email_data = $('#email-user form').serializeArray();
        $.post($('#email-user form').attr('action'), $('#email-user form').serialize(), function (data) {
            if (data.result) {
                var error = $('<div class="alert alert-success alert-dismissable">\n' +
                    '  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>\n' +
                    '  {0}\n'.format(data.message) +
                    '</div>');
                $('#email-user-errors').append(error);
            }
            else {
                var error = $('<div class="alert alert-danger alert-dismissable">\n' +
                    '  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>\n' +
                    '  {0}\n'.format(data.message) +
                    '</div>');
                $('#email-user-errors').append(error);
            }
        });
    });

    $('.edit-team').click(function () {
        var elem = $(this).parent().parent().parent();
        var id = elem.find('.team-id').attr('value') || '';
        var name = elem.find('.team-name').attr('value') || '';
        var email = elem.find('.team-email').attr('value') || '';
        var website = elem.find('.team-website > a').attr('href') || '';
        var affiliation = elem.find('.team-affiliation').attr('value') || '';
        var country = elem.find('.team-country').attr('value') || '';

        var admin = elem.find('.team-admin').attr('value') == 'True' || false;
		var verified = elem.find('.team-verified').attr('value') == 'True' || false;
		var hidden = elem.find('.team-hidden').attr('value') == 'True' || false;

        load_update_modal(id, name, email, website, affiliation, country, admin, verified, hidden);
    });

    $('.create-team').click(function () {
        load_update_modal('new', '', '', '', '', '', false, false, false);
    });

    $('.delete-team').click(function () {
        var elem = $(this).parent().parent().parent();
        var team_id = elem.find('.team-id').text().trim();
        var name = htmlentities(elem.find('.team-name').text().trim());

        var td_row = $(this).parent().parent().parent();

        ezq({
            title: "Delete User",
            body: "Are you sure you want to delete {0}".format("<strong>" + name + "</strong>"),
            success: function () {
                var route = script_root + '/admin/team/' + team_id + '/delete';
                $.post(route, {
                    nonce: nonce,
                }, function (data) {
                    var data = $.parseJSON(JSON.stringify(data));
                    if (data == "1") {
                        td_row.remove();
                    }
                });
            }
        })
    });


    $('.email-team').click(function () {
        var elem = $(this).parent().parent().parent();
        var id = elem.find('.team-id').text().trim();
        load_email_modal(id);
    });

});
</script>
{% endblock %}
